package com.wxg.controller;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/common")
public class CommonController {
	
	@Resource
	private DataSource dataSource;

	@RequestMapping(value = "/druidDemo", method = { RequestMethod.POST, RequestMethod.GET })
	public Object druidDemo(HttpServletRequest request){
		Map<String,Object> result = new HashMap<String,Object>();
		result.put("errorCode", "0");
		result.put("msg", "invoke druidDemo...");
		
		System.out.println("===");
		System.out.println( dataSource );
		
		druidTest(result);
		
		return result;
	}
	
	
	private void druidTest(Map<String,Object> result){
		DataSource ds = dataSource;
		
		String sql = null;
		try {
			Map<String,String> sqlMap = new LinkedHashMap<String,String>();
			sqlMap.put("api_app", "SELECT COUNT(1) FROM api_app");
			sqlMap.put("api_interface", "SELECT COUNT(1) FROM api_interface");
			sqlMap.put("api_sub_interface", "SELECT COUNT(1) FROM api_sub_interface");
			sqlMap.put("api_user", "SELECT COUNT(1) FROM api_user");
			
			for(int i=0;i<5;i++){
				for(String key : sqlMap.keySet()){
					
					Connection conn = ds.getConnection();
					System.out.println(String.format("=========conn: %s", conn.hashCode()));
					Statement stmt = conn.createStatement();
					sql = sqlMap.get(key);
					ResultSet rs = stmt.executeQuery(sql);
					while(rs.next()){
						System.out.println(String.format("%s count: %s", key, rs.getString(1)));
					}
					conn.close();
					
				}
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			result.put("errorCode", "1");
			result.put("msg", "[Error] invoke druidDemo..."+e.getMessage());
		}
	}
}
